package cn.renhui.hermesbus.response;

import com.google.gson.Gson;

import cn.renhui.hermesbus.core.ObjectCenter;
import cn.renhui.hermesbus.Request;
import cn.renhui.hermesbus.Response;
import cn.renhui.hermesbus.core.TypeCenter;
import cn.renhui.hermesbus.bean.RequestBean;
import cn.renhui.hermesbus.bean.RequestParameter;
import cn.renhui.hermesbus.bean.ResponseBean;

public abstract class ResponceMake {

    protected static final ObjectCenter OBJECT_CENTER = ObjectCenter.getInstance();

    // UserManager的Class
    protected Class<?> reslutClass;

    // getInstance()参数数组
    protected Object[] mParameters;

    Gson GSON = new Gson();

    protected TypeCenter typeCenter = TypeCenter.getInstance();

    protected abstract Object invokeMethod();

    protected abstract void setMethod(RequestBean requestBean);

    public Response makeResponce(Request request) {
        RequestBean requestBean = GSON.fromJson(request.getData(), RequestBean.class);
        reslutClass = typeCenter.getClassType(requestBean.getResultClassName());
        //参数还原
        RequestParameter[] requestParameters = requestBean.getRequestParameters();
        if (requestParameters != null && requestParameters.length > 0) {
            mParameters = new Object[requestParameters.length];
            for (int i = 0; i < requestParameters.length; i++) {
                RequestParameter requestParameter = requestParameters[i];
                Class<?> clazz = typeCenter.getClassType(requestParameter.getParameterClassName());
                mParameters[i] = GSON.fromJson(requestParameter.getParameterClassValue(), clazz);
            }
        } else {
            mParameters = new Object[0];
        }

        setMethod(requestBean);
        Object resultObject = invokeMethod();

        ResponseBean responceBean = new ResponseBean(resultObject);
        String data = GSON.toJson(responceBean);
        Response response = new Response(data);
        return response;
    }
}
